import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.Level;

import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class MinaServer {
	private static Logger logger = LoggerFactory.getLogger(MinaServer.class);
	private int port;
	private ConcurrentLinkedQueue<IoSession> session_table = new ConcurrentLinkedQueue<IoSession>();
	
	public MinaServer(int port){
		java.util.logging.Logger.getGlobal().setLevel(Level.WARNING);
		this.port = port;
		IoAcceptor acceptor = new NioSocketAcceptor();  //创建nio socket监听
		//acceptor.getFilterChain().addLast("logger", new LoggingFilter());  //添加日志过滤器
		acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("utf-8"))));  //指定编码过滤器
		acceptor.setHandler(new MyHandler());
		try {
			acceptor.bind(new InetSocketAddress(port));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			logger.error("socket error:"+e.getMessage());
		}
	}
	
	class MyHandler extends IoHandlerAdapter{

		@Override
		public void messageReceived(IoSession session, Object message)
				throws Exception {
			//接收到消息，则对其他客户端进行广播
			Iterator<IoSession> itr = session_table.iterator();
			while(itr.hasNext()){
				IoSession s = itr.next();
				if(!session.equals(s)){
					s.write(message);
				}
			}
			
		}

		@Override
		public void sessionClosed(IoSession session) throws Exception {
			// 移除出消息列表
			session_table.remove(session);
		}

		@Override
		public void sessionCreated(IoSession session) throws Exception {
			//加入消息列表
			session_table.offer(session);
			
		}

		@Override
		public void sessionOpened(IoSession session) throws Exception {
			// TODO Auto-generated method stub
			super.sessionOpened(session);
		}
		
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new MinaServer(9901);
	}

}
